package com.sinodata.bsm.cicp.collector.tlq;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CollectorUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: Tonglink采集程序， 用于采集用于采集指定 tlqName 和 业务代码的 连接状态， ip 和端口
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-26 AM 9:59:33    liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class TLQCollector extends Collector {

    private static final Logger logger = Logger.getLogger(TLQCollector.class);

    /**
     * 采集方法
     * 
     * @param ip 执行命令的主机ip地址
     * @return 资源列表
     * @throws CollectorException 
     * @throws IOException
     */
    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> resProValList = null;
        BufferedReader reader = null;
        getPropMeta();
        try {
            reader = CollectorUtil.getReader("tlqstat -lZ 1", ip);
            resProValList = this.parseReader(reader);
        } catch (IOException e) {
            logger.error("Failed to collector TLQ ", e);
            throw new CollectorException("Failed to close IO Resource ", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("Failed to close IO resource ", e);
                    throw new CollectorException("Failed to close IO Resource ", e);
                }
            }
        }
        return resProValList;
    }

    /**
     * 解析 reader 获取 资源列表
     * 
     * @param reader
     * @return
     * @throws IOException
     */
    private List<ResPropertyValue> parseReader(BufferedReader reader) throws IOException {
        List<ResPropertyValue> resProValList = null;
        String typeStr = this.getParamMap().get(getParamMeta()[0]);
        String busCode = this.getParamMap().get(getParamMeta()[1]);
        // 匹配： [TLQ3619]
        Pattern typePatn = Pattern.compile(".*\\[(\\S+)\\]\\s*");
        // 匹配：[xxxx] ----------CONNECT IP=xxx PORT=xxxx
        Pattern codePatn = Pattern.compile(".*\\[(\\S+)\\].*\\-{5,}+(\\w{7})\\sIP=(.*)\\sPORT\\=(.*)\\s*");
        // 匹配：[xxxx] ----------DISCONN
        Pattern codePatn2 = Pattern.compile("^.*\\[(\\S+)\\].*\\-{5,}+(\\w{7})\\s*$");
        String[] propMetas = getPropMeta();
        String tmp = null;
        Matcher typeMach = null;
        Matcher propMach = null;
        Matcher propMach2 = null;
        while ((tmp = reader.readLine()) != null) {
            typeMach = typePatn.matcher(tmp);
            propMach = codePatn.matcher(tmp);
            propMach2 = codePatn2.matcher(tmp);
            if (tmp.indexOf("<Self>:") > -1 || tmp.indexOf("<To Down>:") > -1) {
                continue;
            } else if (tmp.indexOf("------") > -1 && resProValList != null) {
                if (propMach.matches()) {
                    if (busCode.indexOf(propMach.group(1)) > -1) {
                        ResPropertyValue propertyValueX = new ResPropertyValue();
                        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
                        for (int j = 0; j <= 2; j++) {
                            propValues[j] = ResPropertyValue.createPropValue(propMach.group(j + 2), propMetas[j]);
                        }
                        propertyValueX.setValues(propValues);
                        resProValList.add(propertyValueX);
                    }
                }
                if (propMach2.matches()) {
                    if (busCode.indexOf(propMach2.group(1)) > -1) {
                        ResPropertyValue propertyValueX = new ResPropertyValue();
                        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[3];
                        propValues[0] = ResPropertyValue.createPropValue(propMach2.group(2), propMetas[0]);
                        propValues[1] = ResPropertyValue.createPropValue("N/A", propMetas[1]);
                        propValues[2] = ResPropertyValue.createPropValue("N/A", propMetas[2]);
                        propertyValueX.setValues(propValues);
                        resProValList.add(propertyValueX);
                    }
                }
            } else if (typeMach.matches()) {
                if (typeStr.indexOf(typeMach.group(1)) > -1) {
                    resProValList = new ArrayList<ResPropertyValue>();
                }
            }
        }
        return resProValList;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "tlqName", "busCode" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "Connect Stat", "IP", "Port" };
    }

}
